extends KinematicBody2D

const EnemyDeathEffect = preload("res://Effects/EnemyDeathEffect.tscn")

export (int) var ACCELERATION = 300
export (int) var MAX_SPEED = 50
export (int) var FRACTION = 200
export (float) var INVINCIBAL_DURATION = 0.4

enum {
	IDLE
	WANDER
	CHASE
}

var velocity = Vector2.ZERO
var knockback = Vector2.ZERO

var state = IDLE

onready var stats = $"Stats"
onready var playerDetectionZone = $PlayerDetectionZone
onready var batAnimSprite = $AnimatedSprite
onready var hurtbox = $HurtBox
onready var softCollision = $SoftCollision
onready var wanderController = $WanderConroller
onready var animationPlayer = $AnimationPlayer

func _ready():
	state = pick_random_state([IDLE, WANDER])

func _physics_process(delta):
	knockback = knockback.move_toward(Vector2.ZERO, 200 * delta)
	knockback = move_and_slide(knockback)
	match state:
		IDLE:
			velocity = velocity.move_toward(Vector2.ZERO, FRACTION *delta)
			seek_player()
			try_change_state()
		WANDER:
			seek_player()
			try_change_state()
			if global_position.distance_to(wanderController.target_position) < 4:
				velocity = velocity.move_toward(Vector2.ZERO, ACCELERATION * delta)
			else:
				accelerate_towards_point(wanderController.target_position, delta)
		CHASE:
			var player = playerDetectionZone.player
			if player != null:
				accelerate_towards_point(player.global_position, delta)
			else:
				state = IDLE

	if softCollision.is_colliding():
		velocity += softCollision.get_push_vector() * delta * 400
	velocity = move_and_slide(velocity)	

func try_change_state():
	if wanderController.get_time_left() == 0:
		state = pick_random_state([IDLE, WANDER])
		wanderController.start_wander(rand_range(1, 3))

func accelerate_towards_point(point, delta):
	var direction = global_position.direction_to(point)
	velocity = velocity.move_toward(direction * MAX_SPEED, ACCELERATION * delta)
	batAnimSprite.flip_h = direction.x < 0

func seek_player():
	if playerDetectionZone.can_see_palyer():
		state = CHASE

func pick_random_state(state_list):
	state_list.shuffle()
	return state_list.pop_front()

func _on_HurtBox_area_entered(area):
	stats.health -= area.damage
	knockback = area.knockback_vector * 120
	hurtbox.create_hit_effect()
	hurtbox.start_invincibility(INVINCIBAL_DURATION)


func _on_Stats_no_health():
	queue_free()
	var enemyDeathEffect = EnemyDeathEffect.instance()
	enemyDeathEffect.global_position = global_position
	get_parent().add_child(enemyDeathEffect)


func _on_HurtBox_invincibility_started():
	animationPlayer.play("Start")


func _on_HurtBox_invincibility_ended():
	animationPlayer.play("Stop")
